package com.example.myproject.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.myproject.common.ResponseData;
import com.example.myproject.dto.*;
import com.example.myproject.dto.torrent.*;
import com.example.myproject.dto.torrent.TorrentRecommendationDTO;
import com.example.myproject.model.DownloadRecord;
import com.example.myproject.model.Tag;
import com.example.myproject.model.Torrent;
import com.example.myproject.security.JwtAuthenticationFilter;
import com.example.myproject.service.RecommendationService;
import com.example.myproject.service.TorrentService;
import com.example.myproject.vo.ApiResponse;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/torrent")
@AllArgsConstructor
public class TorrentController {

    private final TorrentService torrentService;
    private RecommendationService recommendationService;

    @PostMapping("/upload-file")
    public ResponseEntity<?> uploadFromFile(
            @RequestParam("torrent_name") String name,
            @RequestParam("category_id") Long categoryId,
            @RequestParam(value = "torrent_description", required = false) String description,
            @RequestPart("file") MultipartFile file,
            @RequestParam(value = "tag", required = false) List<Long>  tags,
            @RequestParam(value = "origin_price", required = false) Double originPrice,
            @RequestParam(value = "download_limit", required = false) Integer downloadLimit,
            @AuthenticationPrincipal JwtAuthenticationFilter.UserPrincipal principal
    ) {
        Long torrentId = torrentService.uploadFile(principal.getId(), name, categoryId, description, file, tags, originPrice, downloadLimit);
        return ResponseEntity.ok(ResponseData.success(torrentId));
    }

    @PostMapping("/upload-torrent")
    public ResponseEntity<?> uploadFromTorrentFile(
            @RequestParam("torrent_name") String name,
            @RequestParam("category_id") Long categoryId,
            @RequestParam(value = "torrent_description", required = false) String description,

            @RequestPart("torrent_file") MultipartFile file,

            @RequestParam(value = "tag", required = false) List<Long>  tags,
            @RequestParam(value = "origin_price", required = false) Double originPrice,
            @RequestParam(value = "download_limit", required = false) Integer downloadLimit,
            @AuthenticationPrincipal JwtAuthenticationFilter.UserPrincipal principal
    ) {
        System.out.println("Upload called, file size = " + file.getSize());
        Long torrentId = torrentService.uploadTorrent(principal.getId(), name, categoryId, description, file, tags, originPrice, downloadLimit);
        return ResponseEntity.ok(ResponseData.success(torrentId));
    }


    @GetMapping("/download/{torrentId}")
    public ResponseEntity<?> downloadTorrent(
            @PathVariable Long torrentId,
            @AuthenticationPrincipal JwtAuthenticationFilter.UserPrincipal principal // 下载记录绑定用户
    ) {
        DownloadUrlDTO dto = torrentService.initiateDownload(torrentId, principal.getId());
        return ResponseEntity.ok(ResponseData.success(dto));
    }

    @PostMapping("/download/{torrentId}")
    public ResponseEntity<?> notifyDownloadComplete(
            @PathVariable Long torrentId,
            @RequestBody DownloadNotifyDTO notifyDto,
            @AuthenticationPrincipal JwtAuthenticationFilter.UserPrincipal principal // 可选校验
    ) {
        torrentService.completeDownload(torrentId, notifyDto, principal.getId());
        return ResponseEntity.ok(ResponseData.success());
    }

    //查询（模糊查询
    @GetMapping("/search")
    public ResponseEntity<?> searchTorrents(SearchTorrentsDTO params) {
        PagedResult<TorrentVO> result = torrentService.search(params);
        return ResponseEntity.ok(ResponseData.success(result));
    }

    //查找
    @GetMapping("/by-tag")
    public ResponseEntity<?> getByTag(@RequestParam("tag_name") String tagName) {
        List<TorrentVO> list = torrentService.byTag(tagName);
        return ResponseEntity.ok(ResponseData.success(list));
    }

    //查找
    @GetMapping("/by-category")
    public ResponseEntity<?> getByCategory(@RequestParam("category_id") Integer categoryId) {
        List<TorrentVO> list = torrentService.byCategory(categoryId);
        return ResponseEntity.ok(ResponseData.success(list));
    }

    //排序
    @GetMapping("/sort-by-upload-time")
    public ResponseEntity<?> sortByUploadTime(@RequestParam(value = "order", defaultValue = "desc") String order,
                                              @RequestParam(value = "page", defaultValue = "1") Integer page,
                                              @RequestParam(value = "size", defaultValue = "10") Integer size) {
        List<TorrentVO> list = torrentService.sortByUploadTime(order, page, size);
        return ResponseEntity.ok(ResponseData.success(list));
    }

    //排序
    @GetMapping("/sort-by-downloads")
    public ResponseEntity<?> sortByDownloads(@RequestParam(value = "order", defaultValue = "desc") String order,
                                             @RequestParam(value = "page", defaultValue = "1") Integer page,
                                             @RequestParam(value = "size", defaultValue = "10") Integer size) {
        List<TorrentVO> list = torrentService.sortByDownloads(order, page, size);
        return ResponseEntity.ok(ResponseData.success(list));
    }


    //类似种子推荐
    @GetMapping("/similar/{torrentId}")
    public CommonResponse<List<Torrent>> getSimilarTorrents(
            @PathVariable Long torrentId,
            @RequestParam(defaultValue = "5") int limit) {
        List<Torrent> recommendations = recommendationService.getSimilarTorrents(torrentId, limit);
        return CommonResponse.success(recommendations);
    }

    //个性化推荐
    //主页显示
    @GetMapping("/recommend")
    public CommonResponse<Page<TorrentRecommendationDTO>> getPersonalizedRecommendations(
            @AuthenticationPrincipal JwtAuthenticationFilter.UserPrincipal principal,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        if (principal == null) {
            return CommonResponse.fail("请先登录");
        }

        Page<TorrentRecommendationDTO> recommendations = recommendationService.getPersonalizedRecommendations(
                principal.getId(), page, size
        );

        // 过滤掉状态不为 normal 的推荐项
        List<TorrentRecommendationDTO> filteredList = recommendations.getRecords().stream()
                .filter(dto -> "normal".equalsIgnoreCase(dto.getTorrentStatus()))
                .collect(Collectors.toList());


        recommendations.setRecords(filteredList);

        return CommonResponse.success(recommendations);
    }


    //种子详情
    @GetMapping("/info/{torrentId}")
    public ResponseEntity<?> getTorrentDetail(@PathVariable Long torrentId) {
        TorrentDetailDTO detail = torrentService.getTorrentDetail(torrentId);
        return ResponseEntity.ok(ResponseData.success(detail));
    }


    // 新增：返回所有Tag
    @GetMapping("/tags")
    public ResponseEntity<?> getAllTags() {
        List<Tag> tags = torrentService.getAllTags();
        return ResponseEntity.ok(ApiResponse.success(200, "获取成功", tags));
    }
    // 返回当前用户所有下载记录
    @GetMapping("/download-records")
    public ApiResponse<List<DownloadRecordDTO>> getUserDownloadRecords() {
        org.springframework.security.core.Authentication auth = org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
        Long userId = ((JwtAuthenticationFilter.UserPrincipal) auth.getPrincipal()).getId();

        List<DownloadRecordDTO> records = torrentService.getDownloadRecordsByUserId(userId);
        return ApiResponse.success(200, "获取成功", records);
    }

    /**
     * 根据分类 + 标签过滤种子
     */
    @PostMapping("/filter")
    public ResponseEntity<?> filterTorrents(@RequestBody FilterTorrentsDTO params) {
        PagedResult<TorrentVO> result = torrentService.filterByCategoryAndTags(params);
        return ResponseEntity.ok(ResponseData.success(result));
    }

}